﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;

namespace WebApplication.AppCode
{
    public static class Extensions
    {
        public static string GetDescription(this Enum enumeration)
        {
            string description = enumeration.GetAttributeValue<DescriptionAttribute, string>(x => x.Description);
            if (String.IsNullOrEmpty(description))
            {
                description = enumeration.ToString();
            }
            return description;
        }

        public static V GetAttributeValue<T, V>(this Enum enumeration, Func<T, V> expression) where T : Attribute
        {
            T attribute = enumeration.GetType().GetMember(enumeration.ToString())[0].GetCustomAttributes(typeof(T), false).Cast<T>().FirstOrDefault();
            if (attribute == null)
            {
                return default(V);
            }
            return expression(attribute);
        }

        public static string GetDescription<T>(this string enumberation)
        {
            int num = 0;
            if (!int.TryParse(enumberation, out num)) { return enumberation.ToString(); }
            Enum t = (Enum)Enum.Parse(typeof(T), enumberation);
            return t.GetDescription();
        }
    }
}